package com.tang.model.expresion;

import com.tang.model.expresion.number.abst.IArithmeticInterpreter;
import com.tang.model.expresion.number.impl.NumberInterpreter;
import com.tang.model.expresion.utils.CalculatorUtil;

import java.util.Stack;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/9/6 8:09
 * @Desc 计算器类，是所有的字符串计算的入口
 * @Remarks
 */
public class Calculator {
    private Stack<IArithmeticInterpreter> stack = new Stack<>();

    //    计算表达式
    public Integer calculate(String expression) {
        String[] splits = expression.split(" ");
        for (int i = 0; i < splits.length; i++) {
            String element = splits[i];
            if (CalculatorUtil.isOperator(element)) {
                IArithmeticInterpreter left = stack.pop();
                String right = splits[++i];
                stack.push(CalculatorUtil.createInterpreter(left.getNumber(), Integer.parseInt(right), element));
            } else {
                stack.push(new NumberInterpreter(element));
            }
        }
        return stack.pop().getNumber();
    }
}
